﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.Code;
using Telerik.Web.UI;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.Utilities.LinqToEntities;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;

namespace WebApplication.Controls.Management.Dictionaries
{
	public partial class CityEditControl : EntityUserControl
	{
		protected void Page_Init(object sender, EventArgs e)
		{
			ConfigureSelectProvinceForm();
			GridEditableItem item = this.Parent.NamingContainer as GridEditableItem;
			if (item == null || item.DataItem == null)
			{
				return;
			}

			if (item.DataItem is GridInsertionObject)
			{
				btUpdate.Visible = false;
				return;
			}

			btInsert.Visible = false;
			tbCityName.Text = item["Name"].Text;
			ProvinceIdTextBox.Text = item["ProvinceId"].Text;
			ProvinceNameTextBox.Text = item["ProvinceName"].Text;
			return;
		}

		public DTOCity EditedCity
		{
			get
			{
				DTOCity dtoCity = new DTOCity();
				dtoCity.Name = tbCityName.Text;

				if (string.IsNullOrEmpty(ProvinceIdTextBox.Text))
				{
					return dtoCity;
				}

				dtoCity.Province = new DTOProvince() { Id = int.Parse(ProvinceIdTextBox.Text), Name = ProvinceNameTextBox.Text };
				return dtoCity;
			}
		}

		private void ConfigureSelectProvinceForm()
		{
			RadWindow1.OpenerElementID = SelectProvinceButton.ClientID;
			RadWindow1.OnClientClose = @"
            function(sender, args)
            {
				var province = args.get_argument();
				if (province) {
					$get('" + ProvinceIdTextBox.ClientID + @"').value = province.Id;
					$get('" + ProvinceNameTextBox.ClientID + @"').value = province.Name;
				}
            }
            ";
		}
	}
}